package com.wisdomstar.ws.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wisdomstar.common.exception.base.BaseException;
import com.wisdomstar.ws.domain.Favorites;
import com.wisdomstar.ws.mapper.FavoritesMapper;
import com.wisdomstar.ws.service.FavoritesService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * @author RinMi
 * @since 2023/6/6
 */
@Service
public class FavoritesServiceImpl extends ServiceImpl<FavoritesMapper, Favorites> implements FavoritesService {

    @Resource
    private FavoritesMapper favoritesMapper;

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Override
    public void removeFavorites(Favorites favorites) {
        List<Long> primaryKeyList = favoritesMapper.selectPrimaryKeyRecursion(favorites);
        Favorites fav;
        List<Favorites> favoritesList = new LinkedList<>();
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, Boolean.FALSE);
        FavoritesMapper mapper = sqlSession.getMapper(FavoritesMapper.class);
        try {
            for (Long primaryKey : primaryKeyList) {
                fav = new Favorites();
                fav.setFavoritesId(primaryKey);
                favoritesList.add(fav);
            }
            favoritesList.forEach(mapper::removeFavorites);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public int insertFavorites(Favorites favorites) {
        int count = favoritesMapper.checkFavoritesName(favorites);
        if (count != 0) {
            throw new BaseException("此层级收藏夹名称已存在");
        }
        return favoritesMapper.insertFavorites(favorites);
    }

    @Override
    public int updateFavorites(Favorites favorites) {
        int count = favoritesMapper.checkFavoritesName(favorites);
        if (count != 0) {
            throw new BaseException("此层级收藏夹名称已存在");
        }
        return favoritesMapper.updateFavorites(favorites);
    }

    @Override
    public List<Favorites> listFavorites(Favorites favorites) {
        return favoritesMapper.listFavorites(favorites);
    }
}
